<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-alert show-icon title="注意：只能更改三级参数" type="warning" :closable="false"> </el-alert>
                <!--选择商品分类区  -->
            <el-row>
                <el-col>
                    <span>选择商品分类:</span>
                    <el-cascader v-model="selectedCateKeys" :options="catelist" :props="cateProps" @change="handleChange">
                     </el-cascader>
                </el-col>
            </el-row>  
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 动态参数 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>
                <el-table :data="manyTableDate" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">
                                {{item}}
                            </el-tag>
                            <el-input v-if="scope.row.inputVisible" class="input-new-tag" v-model="scope.row.inputValue" size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"  ref="saveTagInput" >
                            
                            </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <!-- 静态属性 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>
                <el-table :data="onlyTableDate" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">
                                {{item}}
                            </el-tag>
                            <el-input v-if="scope.row.inputVisible" class="input-new-tag" v-model="scope.row.inputValue" size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"  ref="saveTagInput" >
                            
                            </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
           </el-tabs>
        </el-card>

        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 添加参数的对话框 -->
           <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>     
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 修改参数的对话框 -->
           <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>     
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>


<script>
export default {
    data(){
        return{
            catelist:[],
            cateProps:{
                expandTrigger: 'hover',
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            // 级联选择框双向绑定得数组
            selectedCateKeys:[],
            // 被激活得页签绑定得名字
            activeName:'many',
            manyTableDate:[],
            onlyTableDate:[],
            addDialogVisible:false,
            editDialogVisible:false,
        //    添加表单的数据对象
           addForm:{
               attr_name:''
            },
           editForm:{
               attr_name:'',
               attr_id:0
            },
        // 添加表单校验的验证规则对象
            addFormRules:{
                attr_name:[
                    {required:true,message:'请输入参数名称',trigger:'blur'}
                ]
            },
            editFormRules:{
                attr_name:[
                    {required:true,message:'请输入参数名称',trigger:'blur'}
                ]
            },
            // 控制按钮和文本框的隐藏和显示
           
            
       }

    },
    computed:{
        isBtnDisabled(){
            if(this.selectedCateKeys.length!==3){
                return true
            }else{
                return false
            }
        },
        cateId(){
            if(this.selectedCateKeys.length===3){
                return this.selectedCateKeys[2]
            }
            return null
        },
        titleText(){
            if(this.activeName==='many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }


    },
    created(){
        this.getCateList()
    },
    methods:{
       async getCateList(){
        const {data:res} =  await this.$http.get('categories')
        if(res.meta.status!==200) return this.$message.error('获取失败')
        this.catelist = res.data
        // console.log(this.catelist)
        },
        // 级联选择框数据变化会调用这个函数
        handleChange(){
            this.getParamsDate()
        
        },
        handleTabClick(){
            this.getParamsDate()
        },
    
        // 获取参数的列表数据
       async getParamsDate(){
            if(this.selectedCateKeys.length!==3){
               this.selectedCateKeys=[]
               this.manyTableDate=[]
               this.onlyTableDate=[]
               return 
            }
            // console.log(this.selectedCateKeys)
            // 根据所选分类的id 和当前所处的面板,获得对应请求的参数
              const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
                if(res.meta.status!==200) return this.$message.error("错误")
                res.data.forEach(item=>{
                   item.attr_vals = item.attr_vals?item.attr_vals.split(' '):[]
                // 给每个文本框增加自己的显示和数据
                    item.inputVisible = false
                    item.inputValue = ''
               })
                console.log(res.data)
                if(this.activeName === 'many'){
                    this.manyTableDate = res.data
                }else{
                    this.onlyTableDate = res.data
                }
        },
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        addParams(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName
                })
              
                if(res.meta.status!==201){
                    return this.$message.error("添加失败")
                }
                this.$message.success("添加成功")
                this.addDialogVisible = false
                this.getParamsDate()
            })
        },
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        
        addParams(){
            
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName,
                })
              
                if(res.meta.status!==201){
                    return this.$message.error("添加失败")
                }
                this.$message.success("添加成功")
                this.addDialogVisible = false
                this.getParamsDate()
            })
        },
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        editParams(){
            this.$refs.editFormRef.validate(async valid=>{
                
                if(!valid) return
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                    attr_sel:this.activeName,
                    attr_name:this.editForm.attr_name
                })
                console.log(res)
                if(res.meta.status!==200){
                    return this.$message.error("修改失败")
                }
                this.$message.success("修改成功")
                this.editDialogVisible = false
                this.getParamsDate()
            })
        },
        // 点击按钮添加修改对话框
       async showEditDialog(attr_id){
        const {data:res} =  await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}})
            if(res.meta.status!==200) return this.$message.error('失败')
            this.editForm = res.data
             this.editDialogVisible = true
             this.editForm.attr_id=attr_id
        },
        deleteParams(attr_id){
            this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
       const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        if(res.meta.status===200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getParamsDate()
        }
        else{
          this.$message({
            type: 'success',
            message: '删除失败!'
          });
        }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        },
       async handleInputConfirm(row){
            if(row.inputValue.trim().length===0){
                row.inputValue= ''
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue= ''
        // 调用接口 发起请求
             this.saveAttrVals(row)
             row.inputVisible = false
        },
        // 抽取的方法 将对attr_vals保存到数据库
       async saveAttrVals(row){
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                  attr_name:row.attr_name,
                  attr_sel:row.attr_sel,
                  attr_vals:row.attr_vals.join(' ')
              })
              if(res.meta.status!==200) return this.$message.error('操作失败')
              this.$message.success('操作成功')
        },
        showInput(row){
            row.inputVisible = true
            this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
        });
        },
        // 删除对应的参数和选项
        handleClose(index,row){
            row.attr_vals.splice(index,1)
            this.saveAttrVals(row)
        },

    },
}
</script>

<style scoped>
.el-row{
    margin: 15px 0px;
}
.el-tag{
margin:7px
}
.input-new-tag{
    width: 100px;
}
</style>